package com.example.module_mvp.view

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.ListView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.module_mvp.R
import com.example.module_mvp.bean.UserBean
import com.example.module_mvp.model.UserRepositoryImpl
import com.example.module_mvp.presenter.UserPresenterImpl

/**
 * 优点：
 *   1. 结构清晰，职责划分清晰
 *   2. 模块间充分解耦
 *   3. 有利于组件的重用
 * 缺点：
 *   1. 会引入大量的接口，导致项目文件数量激增
 *   2. 增大代码结构复杂性
 */
class MVPActivity: AppCompatActivity(), IUserView {

    private lateinit var presenter: UserPresenterImpl
    private lateinit var adapter: ArrayAdapter<UserBean>

    private lateinit var etUserName: EditText
    private lateinit var btnAddUser: Button
    private lateinit var lvUsers: ListView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_mvp)

        // 初始化Presenter
        val userRepository = UserRepositoryImpl()
        presenter = UserPresenterImpl(userRepository)
        presenter.attachView(this)

        initViews()
        setupListView()

    }

    private fun initViews(){
        etUserName = findViewById(R.id.etUserName)
        btnAddUser = findViewById(R.id.btnAddUser)
        lvUsers = findViewById(R.id.lvUsers)

        btnAddUser.setOnClickListener {
            val name = etUserName.text.toString()
            presenter.addUser(name)
        }
    }

    private fun setupListView(){
        adapter = object : ArrayAdapter<UserBean>(
            this,
            android.R.layout.simple_list_item_1,
            mutableListOf() // 初始为空，通过Presenter加载数据
        ) {
            override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
                val view = super.getView(position, convertView, parent)
                val text = view.findViewById<TextView>(android.R.id.text1)
                text.text = getItem(position)?.name
                return view
            }
        }
        lvUsers.adapter = adapter
    }

    override fun showUser(users: List<UserBean>) {
        adapter.clear()
        adapter.addAll(users)
        adapter.notifyDataSetChanged()
    }

    override fun clearInput() {
        etUserName.setText("")
    }

    override fun showError(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }

}